package com.segersten.kalaha;

import com.google.appengine.api.memcache.MemcacheServiceFactory
import com.google.appengine.api.memcache.MemcacheService

class BoardSessionCache {

	private static final String CACHE_NAME = "BoardSessionCache"
	
	
	def put = { BoardSession session -> 
		
		MemcacheService cache = MemcacheServiceFactory.getMemcacheService(CACHE_NAME)
	    if (!cache) {
	    		throw new RuntimeException("Failed to look up BoardSessionCache")
	    }
	    if (!session) {
	    		throw new IllegalArgumentException("Cannot add object to 'BoardSessionCache' - Session cannot be null");
	    }
	    if (!session.sessionId) {
	    		throw new IllegalArgumentException("Cannot add object to 'BoardSessionCache' - SessionId cannot be null");
	    }
	    if (!session.player1) {
	    		throw new IllegalArgumentException("Cannot add object to 'BoardSessionCache' - Player 1 cannot be null");
	    }
	    if (!session.player2) {
	    		throw new IllegalArgumentException("Cannot add object to 'BoardSessionCache' - Player 2 cannot be null");
	    }
	    
	    cache.put(session.sessionId, session)
	}
	
	def get = { String sessionId ->
		MemcacheService cache = MemcacheServiceFactory.getMemcacheService(CACHE_NAME)
	    if (!cache) {
	    		throw new RuntimeException("Failed to look up BoardSessionCache")
	    }
	    cache.get(sessionId)
	}
	
	def remove = { String sessionId ->
		MemcacheService cache = MemcacheServiceFactory.getMemcacheService(CACHE_NAME)
		if (!cache) {
				throw new RuntimeException("Failed to look up BoardSessionCache")
		}
		cache.delete(sessionId)
	}
	
	def stats = {
    	MemcacheService cache = MemcacheServiceFactory.getMemcacheService(CACHE_NAME)
	    if (!cache) {
	    		render(text:"Failed to get 'BoardSessionCache")
	    		return null
	    }
    	[itemCount:cache.statistics.itemCount]
    }

}
